﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Json;

namespace FlickrGrabbr.Model
{
    public class Photos : IPhotos
    {
        private List<Photo> _photoList = new List<Photo>();

        public Photos()
        {
        }

        public List<Photo> PhotoList
        {
            get { return _photoList; }
            set { _photoList = value; }
        }

        public async Task Update()
        {
            _photoList.Clear();

            JsonValue jsonVal = await FlickrFetcher.TopPlaces();
            System.Diagnostics.Debug.WriteLine(jsonVal.ToString());
            JsonArray jsonPhotoArray =  (JsonArray)jsonVal["photos"]["photo"];

            foreach (JsonValue jsonPhoto in jsonPhotoArray)
            {
                Photo aPhoto = ParseJsonPhoto(jsonPhoto);
                if (aPhoto != null)
                {
                    _photoList.Add(aPhoto);
                }
            }
        }

        private static Photo ParseJsonPhoto(JsonValue jsonPhoto)
        {
            Photo photo = null;

            if (jsonPhoto.JsonType == JsonType.Object)
            {
                photo = new Photo();
                JsonObject obj = (JsonObject)jsonPhoto;
                JsonValue val;
                photo.ID = (obj.TryGetValue("id", out val)) ? StringFromJsonValue(val) : String.Empty;
                photo.Title = (obj.TryGetValue("title", out val)) ? StringFromJsonValue(val) : String.Empty;
                photo.Description = String.Empty;
                JsonValue val2ndLevel;
                if (obj.TryGetValue("description", out val2ndLevel))
                {
                    if (val2ndLevel.JsonType == JsonType.Object)
                    {
                        JsonObject obj2ndLevel = (JsonObject)val2ndLevel;
                        photo.Description = (obj2ndLevel.TryGetValue("_content", out val)) ? StringFromJsonValue(val) : String.Empty;
                    }
                }

                photo.Farm = (obj.TryGetValue("farm", out val)) ? StringFromJsonValue(val) : String.Empty;
                photo.Server = (obj.TryGetValue("server", out val)) ? StringFromJsonValue(val) : String.Empty;
                photo.Secret = (obj.TryGetValue("secret", out val)) ? StringFromJsonValue(val) : String.Empty;
                photo.OriginalSecret = (obj.TryGetValue("originalsecret", out val)) ? StringFromJsonValue(val) : String.Empty;
            }
            return photo;
        }

        private static string StringFromJsonValue(JsonValue val)
        {
            return val.ToString().Replace("\"", "");
        }

        private static int IntFromJsonValue(JsonValue val)
        {
            return Int32.Parse(StringFromJsonValue(val));
        }

    }
}
